<script setup>

import {Delete, Edit, Plus} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {useUserInfoStore} from "@/stores/userInfo";
import {deleteGoods, getGoodsList, insertGoods, updateGoods} from "@/api/goods";
import {ElMessage, ElMessageBox} from "element-plus";
//分页条数据模型
// const pageNum = ref(1)//当前页
// const total = ref(20)//总条数
// const pageSize = ref(5)//每页条数
const dialogFormVisible = ref(false)
const titleName = ref('')
// const userInfoStore = useUserInfoStore();

const drawerVisible = ref(false)
const imageUrl = ref('')

const pageNum = ref(1); // 当前页
const total = ref(0); // 总条数（初始为 0，后端返回后更新）
const pageSize = ref(5); // 每页条数
const goodsList = ref([]); // 商品列表数据
const userInfoStore = useUserInfoStore();

// 文件上传回调
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  formData.value.image = response.message
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/png') {
    ElMessage.error('只能上传图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const formData = ref({
  productId: 0,
  name: '',
  price: 0,
  status: 0,
  description: '',
  image: ''
})
const form = ref(null)
const formLabelWidth = '140px'

// 获取商品列表
const fetchGoodsList = () => {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      name:formData.value.name,
      price:formData.value.price,
      status:formData.value.status,
      description:formData.value.description,
      image:formData.value.image,
    };
    getGoodsList(params).then((res) => {
      goodsList.value=res.data
    })

};

// 初始化加载数据
onMounted(() => {
  fetchGoodsList();
});

// 分页切换
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchGoodsList();
};

const handleCurrentChange = (newPage) => {
  pageNum.value = newPage;
  fetchGoodsList();
};

// 添加商品打开抽屉
const showAddDrawer = (title) => {
  titleName.value = title
  drawerVisible.value = true
}

//添加商品发送请求
const addGoods=()=>{
  form.value.validate((valid)=>{
    if (valid) {
      insertGoods(formData.value).then(res=>{
        if (res.success) {
          ElMessage.success(res.message)
          drawerVisible.value = false
          fetchGoodsList()
        }
      })
    }
  })
}

// 商品编辑
const showEditDrawer = (row, title) => {
  formData.value = {...row}
  imageUrl.value = `/api/file/download.do?filename=${row.picture}`
  titleName.value = title
  drawerVisible.value = true
}
// 编辑商品发送请求
const editGoods=()=>{
  form.value.validate((valid)=>{
    if (valid) {
      updateGoods(formData.value).then(res=>{
        if (res.success) {
          ElMessage.success(res.message)
          drawerVisible.value = false
          fetchGoodsList()
        }
      })
    }
  })
}

// 商品删除
const deleteById = (productId) => {
  ElMessageBox.confirm(
      '确认删除吗，删除后不可恢复?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteGoods({productId:productId}).then(res=>{
          if (res.success) {
            ElMessage.success(res.message)
            fetchGoodsList()
          }
        })
      })
      .catch(() => {
      })
}

// 取消关闭抽屉
const cancelClick=(formEl)=>{
  drawerVisible.value = false
  formEl.resetFields()
}

const rules = {
  name: [
    {required: true, message: '请输入商品名', trigger: 'blur'},
  ],
  price: [
    {required: true, message: '请输入价格', trigger: 'blur'},
  ],
  status: [
    {required: true, message: '请选择是否上架', trigger: 'change'},
  ],
  description: [
    {required: true, message: '请输入简介', trigger: 'blur'},
  ],
  image: [
    {required: true, message: '请上传图片', trigger: 'change'},
  ]
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>商品管理</span>
        <div class="extra">
          <el-button type="primary" @click="showAddDrawer('添加商品')">添加商品</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
<!--    <el-form inline>-->
<!--      <el-form-item label="用户名：">-->
<!--        <el-input v-model="username" placeholder="请输入用户名"></el-input>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="性别：">-->
<!--        <el-select placeholder="请选择" v-model="gender">-->
<!--          <el-option label="男" value="男"></el-option>-->
<!--          <el-option label="女" value="女"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" @click="getUserList">搜索</el-button>-->
<!--        <el-button @click="resetParams">重置</el-button>-->
<!--      </el-form-item>-->
<!--    </el-form>-->
    <!-- 商品列表 -->
    <el-table :data="goodsList" style="width: 100%">
      <el-table-column label="商品ID" prop="productId"></el-table-column>
      <el-table-column label="商品名" prop="name"></el-table-column>
      <el-table-column label="单价" prop="price">
        <template #default="{ row }">
          {{ row.price }} 元
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template #default="{row}">
          <el-tag :type="row.status===1?'success':'danger'">{{row.status===1?'上架中':'已下架'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="简介" prop="description" width="300px"></el-table-column>
      <el-table-column label="图片" prop="image">
        <template #default="{row}">
          <el-image :src="`/api/file/download.do?filename=${row.image}`"
                    :preview-src-list="[`/api/file/download.do?filename=${row.image}`]" hide-on-click-modal></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showEditDrawer(row,'编辑商品')"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteById(row.productId)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>

  <el-drawer v-model="drawerVisible" direction="rtl">
    <template #header>
      <h4>{{titleName}}</h4>
    </template>
    <template #default>
      <el-form ref="form" :rules="rules" :model="formData" label-width="auto" style="max-width: 600px">
        <el-form-item  label="商品名" prop="name">
          <el-input type="text" v-model="formData.name"  />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input type="number" v-model="formData.price"  />
        </el-form-item>
        <el-form-item label="是否上架" prop="status">
          <el-select  placeholder="请选择" v-model="formData.status">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0"  />
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input type="textarea" v-model="formData.description"  />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload
              class="avatar-uploader"
              action="/api/file/upload.do"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick(form)">取消</el-button>
        <el-button type="primary" @click="titleName==='添加商品'?addGoods():editGoods()">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>